package com.demo.controller;

import com.madgag.gif.fmsware.AnimatedGifEncoder;
import com.madgag.gif.fmsware.GifDecoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;

/**
 * @author wangfengchen
 */
public class test {

  public static void main(String[] args) throws IOException {
    // 加载动图
    GifDecoder decoder = new GifDecoder();
    decoder.read(new File("/Users/wangfengchen/Downloads/test/img.gif").getAbsolutePath());

    // 创建AnimatedGifEncoder对象
    AnimatedGifEncoder encoder = new AnimatedGifEncoder();
    encoder.setRepeat(0);
    encoder.start("/Users/wangfengchen/Downloads/test/success.gif");

    double clarity = 7d;
    clarity = clarity > 1 ? 1F : clarity;
    clarity = clarity < 0 ? 0.5F : clarity;
    // 水印
    BufferedImage mark = ImageIO.read(Files.newInputStream(new File("/Users/wangfengchen/Downloads/test/img.png").toPath()));
    for (int i = 0; i < decoder.getFrameCount(); i++) {
      BufferedImage image = decoder.getFrame(i);
      int imgWidth = image.getWidth(null);
      int imgHeight = image.getHeight(null);
      BufferedImage bufImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
      Graphics2D g = bufImg.createGraphics();
      //原图写入
      g.drawImage(image, 0, 0, bufImg.getWidth(), bufImg.getHeight(), null);
      //水印写入
      //设置对线段的锯齿状边缘处理
      g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      //设置水印图的透明度
      g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));

      g.rotate(Math.toRadians(0), (double) bufImg.getWidth() / 4, (double) bufImg.getHeight() / 4);
      // 设置水印图的位置
      g.drawImage(mark, 0, 0, 100, 100, null);
      g.dispose();
      // 添加帧到encoder中
      encoder.addFrame(bufImg);
      encoder.setDelay(decoder.getDelay(i));
    }
    // 完成编码
    encoder.finish();
  }
}
